from fastapi import FastAPI, Depends, Request, Response
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
from sqlalchemy.ext.asyncio import AsyncSession
import time

from app.config import settings
from app.database import get_db
from app.utils.logging import setup_logging, get_logger
from app.core.lifespan import lifespan
from app.core import db_health, monitoring
from app.api import v1, admin
from mangum import Mangum
# 配置日志
setup_logging()
logger = get_logger(__name__)

# 创建FastAPI应用实例
app = FastAPI(
    title=settings.app_name,
    description="多学校课程表数据管理后端系统",
    version="1.0",
    debug=settings.debug,
    lifespan=lifespan,
)

# 添加CORS中间件
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # 在生产环境中应该指定具体的域名
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# 添加请求日志中间件
@app.middleware("http")
async def log_requests(request: Request, call_next):
    start_time = time.time()
    response = await call_next(request)
    process_time = time.time() - start_time
    logger.info(
        f"Request processed",
        path=request.url.path,
        method=request.method,
        process_time_ms=round(process_time * 1000, 2),
        status_code=response.status_code
    )
    return response

# 添加全局异常处理
@app.exception_handler(Exception)
async def global_exception_handler(request: Request, exc: Exception):
    logger.error(
        f"Global exception handler caught exception",
        path=request.url.path,
        method=request.method,
        error=str(exc),
        error_type=type(exc).__name__
    )
    return JSONResponse(
        status_code=500,
        content={"code": 500, "message": "Internal server error", "errors": {"detail": [str(exc)]}}
    )

# 注册健康检查和监控路由
app.include_router(db_health.router)
app.include_router(monitoring.router)

# 注册课程表API路由
app.include_router(v1.router)
app.include_router(admin.router)

@app.get("/")
async def read_root():
    """
    根路径接口
    返回应用基本信息
    """
    logger.info("访问根路径接口")
    return {
        "message": "欢迎使用课程表后端服务",
        "app_name": settings.app_name,
        "version": "1.0.0",
        "status": "running",
    }

@app.get("/health")
async def health_check():
    """
    健康检查接口
    """
    return {"status": "healthy", "app_name": settings.app_name, "version": "1.0.0"}

# 示例：使用缓存装饰器的路由
from app.cache.decorators import cached

@app.get("/demo/cached")
@cached(ttl=60, key_prefix="demo")
async def cached_endpoint(db: AsyncSession = Depends(get_db)):
    """
    示例缓存端点
    演示如何使用缓存装饰器
    """
    # 这里的结果会被缓存60秒
    return {
        "message": "这个响应被缓存了60秒",
        "timestamp": __import__("time").time(),
    }

handler = Mangum(app)